(async function () {
  "use strict";

  const DataRaw = await Promise.all([
    import('../c/path.js'),
    import('../satisfactory/path.js'),
    import('../tex/path.js'),
  ])
  console.log('DataRaw', DataRaw);

  function updatePath(tree, path) {
    const pathConcat = (path ? path + "/" : "")
    if (typeof tree === "string") {
      return {
        text: tree,
        icon: "jstree-file",
        li_attr: { "data-path": pathConcat + tree },
      }
    }
    let ret = { path: tree.path, text: tree.text, children: [] }
    for (const v of tree.children) {
      if (typeof v === "string") {
        ret.children.push({
          text: v,
          icon: "jstree-file",
          li_attr: { "data-path": pathConcat + tree.path + "/" + v },
        })
      }
      else {
        ret.children.push(updatePath(v, pathConcat + tree.path))
      }
    }
    return ret
  }

  let Data = []
  for (let i in DataRaw) {
    console.log(DataRaw[i].default)
    Data[i] = updatePath(DataRaw[i].default, "");
  }
  console.log('Data', Data);

  var $grid = $('.hero-grid').masonry({
    columnWidth: 175,
    itemSelector: '.hero-grid__item'
  });
  // change size of item by toggling gigante class
  $grid.on('click', '.hero-grid__item', function () {
    $(this).toggleClass('grid-item--gigante');
    console.log("cl");
    // trigger layout after item size changes
    $grid.masonry('layout');
  });

  $('.tree').jstree({
    "core": {
      "animation": 0,
      "check_callback": true,
      "themes": { "stripes": true },
      "data": Data
    },
    "types": {
      "#": {
        "max_children": 10,
        "max_depth": 10,
        "valid_children": ["root"]
      },
      "root": {
        "valid_children": ["default", "file"]
      },
      "default": {
        "valid_children": ["default", "file"]
      },
      "file": {
        "icon": "glyphicon glyphicon-file",
        "valid_children": []
      }
    },
    "plugins": [
      "contextmenu",
      // "dnd", // drag & drop
      "search",
      "state",
      "types",
      "wholerow"
    ]
  }).on("changed.jstree", function (e, data) {
    console.log(data.selected);
    let el = document.getElementById(data.selected[0]);
    if (!el) return;
    console.log(el.dataset);
    if (el.dataset.path) {
      let $item = $(`<div class="hero-grid__item"><div class="hero__example-link" style="text-align: center; padding: 4px;"><img src="${el.dataset.path}" style="width: 95%;"/><a class="hero__example-link" href="${el.dataset.path}" target="_blank" style="background:transparent; word-break: break-all;">${el.dataset.path}</a></div></div>`);
      $grid.prepend($item).masonry('prepended', $item);
    }
  });

  window.Data = Data;
})();